package LeftRightMost;

/**
 * User: 86156
 * Date: 2023-04-15
 * Time: 10:26
 */



public class LeftMost {
    public static void main(String[] args) {
        int[] arr = {7, 13, 21, 30,30,30, 38,44, 44, 52, 53};

        int index = LeftBinarySearch2(arr,22);
        System.out.println(index);

        index = RightBinarySearch2(arr,22);
        System.out.println(index);
    }

    // 查找最左边的目标元素
    private static int LeftBinarySearch(int[] arr,int target) {
        int left = 0;
        int right = arr.length-1;
        int index = -1;
        while(left<=right){
            int mid = (left+right)>>>1;

            if(target<arr[mid]){
                right = mid-1;
            }else if(arr[mid] <target){
                left = mid+1;
            }else{
                // 计录候选者
                index = mid;
                // 在左侧方位继续找
                right = mid-1;
            }
        }
        return index;
    }

    // 返回>=target 最靠左的索引位置
    public static int LeftBinarySearch2(int[] arr,int target){
        int left = 0;
        int right = arr.length-1;

        while(left<=right){
            int mid = (left+right)>>>1;

            if(target <= arr[mid]){
                right = mid-1;
            }else {
                left = mid+1;
            }
        }
        return left;
    }


    // 返回<=target 最靠右的索引位置
    public static int RightBinarySearch2(int[] arr,int target) {
        int left = 0;
        int right = arr.length - 1;

        while (left <= right) {
            int mid = (left + right) >>> 1;

            if (target <= arr[mid]) {
                right = mid - 1;
            } else{
                left = mid + 1;
            }
        }
        return right;
    }
}
